<?php
/*
 * @Author: 李明
 * @Date: 2021-11-10 09:36:29
 * @LastEditTime: 2021-12-02 12:24:24
 * @LastEditors: 李明
 * @Description: 
 * @FilePath: /CRM2.0-PHP/app/Http/Controllers/file/ImageContentController.php
 * @山东壹零贰肆信息科技有限公司
 */

namespace App\Http\Controllers\file;

use App\Http\Controllers\common\CommonFun;
use App\Http\Controllers\common\LMReturn;
use App\Http\Controllers\Controller;
use App\Models\Bank;
use App\Models\CustArea;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class ImageContentController extends Controller
{
    /**
     * @description: 身份证识别
     * @param string $img base64图片内容
     * @param string $id_card_side  front：身份证含照片的一面  back：身份证带国徽的一面  自动检测身份证正反面，如果传参指定方向与图片相反，支持正常识别，返回参数image_status字段为"reversed_side"
     * @param string $detect_risk true：开启，请查看返回参数risk_type； false：不开启   是否开启身份证风险类型(身份证复印件、临时身份证、身份证翻拍、修改过的身份证)功能，默认不开启，即：false
     * @param string $detect_card 是否检测身份证进行裁剪，默认不检测。可选值：true-检测身份证并返回证照的 base64 编码及位置信息
     * @param string $detect_photo 是否检测头像内容，默认不检测。可选值：true-检测头像并返回头像的 base64 编码及位置信息
     * @return {*}
     */
    public static function idCardContentImage($path, $id_card_side, $detect_risk = 'false', $detect_card = 'false',  $detect_photo = 'false')
    {
        $token = ImageContentController::biadu_access_token_image();
        $url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=' . $token;
        $img = file_get_contents($path);
        $img = base64_encode($img);
        $bodys = array(
            'image' => $img,
            // 'url' => $image_url,
            'id_card_side' => $id_card_side,
            'detect_risk' => $detect_risk,
            'detect_photo' => $detect_photo,
            'detect_card' => $detect_card,
        );
        $res = ImageContentController::request_post($url, $bodys);
        $res = CommonFun::str_change($res);
        $id_card = [];
        $words_result = $res['words_result'];
        switch ($id_card_side) {
            case 'front': // 正面
                $id_card['name'] = $words_result['姓名']['words'] ?? '';
                $id_card['national'] = $words_result['民族']['words'] ?? '';
                $id_card['address'] = $words_result['住址']['words'] ?? '';
                $id_card['id_number'] = $words_result['公民身份号码']['words'] ?? '';
                $id_card['birthday'] = $words_result['出生']['words'] ?? '';
                $id_card['sex'] = $words_result['性别']['words'] ?? '';
                $id_card['image_status'] = $res['image_status'] ?? '';
                $id_card = ImageContentController::addressContent($id_card);
                break;
            case 'back': // 反面
                $id_card['end_date'] = $words_result['失效日期']['words'] ?? '';
                $id_card['organ'] = $words_result['签发机关']['words'] ?? '';
                $id_card['sign_date'] = $words_result['签发日期']['words'] ?? '';
                $id_card['image_status'] = $res['image_status'] ?? '';
                break;
            default:
                # code...
                break;
        }
        $image_status = $id_card['image_status'] ?? '';
        switch ($image_status) {
            case 'normal':
                $id_card['image_status_str'] = '识别正常';
                break;
            case 'reversed_side':
                $id_card['image_status_str'] = '身份证正反面颠倒';
                break;
            case 'non_idcard':
                $id_card['image_status_str'] = '上传的图片中不包含身份证';
                break;
            case 'blurred':
                $id_card['image_status_str'] = '身份证模糊';
                break;
            case 'other_type_card':
                $id_card['image_status_str'] = '其他类型证照';
                break;
            case 'over_exposure':
                $id_card['image_status_str'] = '身份证关键字段反光或过曝';
                break;
            case 'over_dark':
                $id_card['image_status_str'] = '身份证欠曝（亮度过低）';
                break;
            case 'unknown':
                $id_card['image_status_str'] = '未知状态';
                break;
            default:
                $id_card['image_status_str'] = '识别错误';
                break;
        }
        return $id_card;
    }

    /**
     * @description: 银行卡识别
     * @param string $img base64图片内容
     * @param string $detect_direction  是否检测图像朝向，默认检测，即：true。可选值包括true - 检测朝向；false - 不检测朝向。朝向是指输入图像是正常方向、逆时针旋转90/180/270度。
     * @return {*}
     */
    public static function bankCardContentImage($image_url, $detect_direction = 'true')
    {
        $token = ImageContentController::biadu_access_token_image();
        $url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/bankcard?access_token=' . $token;
        // $img = file_get_contents('[本地文件路径]');
        // $img = base64_encode($img);
        $bodys = array(
            // 'image' => $img,
            'url' => $image_url,
            'detect_direction' => $detect_direction,
        );
        $res = ImageContentController::request_post($url, $bodys);
        $res = CommonFun::str_change($res);
        $bank_name =  $res['result']['bank_name'] ?? '';
        $res['result']['bank'] = Bank::where('bank_name', $bank_name)->orderBy("weight", "desc")->get() ?? [];
        return $res;
    }
    /**
     * @description: 地址识别省市区
     * @param {*} $address
     * @return {*}
     */
    public static function addressContent($id_card)
    {
        $token = ImageContentController::biadu_access_token_text();
        $url = 'https://aip.baidubce.com/rpc/2.0/nlp/v1/address?access_token=' . $token;
        $bodys = array(
            'text' => $id_card['address'],
            'confidence' => 50,
        );
        // $bodysStr = json_decode($bodys);
        $bodysStr = json_encode($bodys);
        $res = ImageContentController::request_post($url, $bodysStr);
        $res = CommonFun::str_change($res);
        $id_card['text_error_code'] = $res['error_code'] ?? '';
        if ($id_card['text_error_code'] != '') {
            return $id_card;
        }
        $id_card['pro'] = $res['province'] ?? '';
        $id_card['pro_code'] = $res['province_code'] ?? '';
        $pro = CustArea::where('area_code', $id_card['pro_code']) ?? false;
        if (!$pro) {
            $pro = new CustArea;
            $pro->area_name = $id_card['pro'];
            $pro->area_code = $id_card['pro_code'];
            $pro->area_parentcode = '000000';
            $pro->area_fullname = $id_card['pro'];
            $pro->area_status = 1;
            $pro->area_level = 0;
            $pro->save();
        }
        $id_card['city'] = $res['city'] ?? '';
        $id_card['city_code'] = $res['city_code'] ?? '';
        $city = CustArea::where('area_code', $id_card['pro_code']) ?? false;
        if (!$city) {
            $city = new CustArea;
            $city->area_name = $id_card['city'];
            $city->area_code = $id_card['city_code'];
            $city->area_parentcode = $pro->area_code;
            $city->area_fullname = $pro->area_name . '/' . $id_card['city'];
            $city->area_status = 1;
            $city->area_level = 1;
            $city->save();
        }
        $id_card['area'] = $res['county'] ?? '';
        $id_card['area_code'] = $res['county_code'] ?? '';
        $area = CustArea::where('area_code', $id_card['pro_code']) ?? false;
        if (!$area) {
            $area = new CustArea;
            $area->area_name = $id_card['county'];
            $area->area_code = $id_card['county_code'];
            $area->area_parentcode = $city->area_code;
            $area->area_fullname = $pro->area_name . '/' . $city->area_name . '/' . $id_card['county'];
            $area->area_status = 1;
            $area->area_level = 2;
            $area->save();
        }
        return $id_card;
    }
    /**
     * @description: 登录百度，获取access_token 用于图片接口
     * @param {*}
     * @return {*}
     */
    public static function biadu_access_token_image()
    {

        $keyToken_worker = 'baidu_token_crm_image';
        $redis_token = Redis::get($keyToken_worker);
        if ($redis_token == null) {
            $post_data['client_id']      = 'G0QSzmu1KM9lELgD78HNAHHd';
            $post_data['client_secret'] = 'u6NNRTf3jSOnVwQMMGApgE9CIzwT5zux';
            $access_token = ImageContentController::baidu_access_token($post_data, $keyToken_worker);
        } else {
            $access_token = $redis_token;
        }
        return $access_token;
    }
    /**
     * @description: 登录百度，获取access_token 用于文字处理接口
     * @param {*}
     * @return {*}
     */
    public static function biadu_access_token_text()
    {

        $keyToken_worker = 'baidu_token_crm_text';
        $redis_token = Redis::get($keyToken_worker);
        if ($redis_token == null) {
            $post_data['client_id']      = 'leawuOBdFr1MtC2xT2N5nfxi';
            $post_data['client_secret'] = 'D5BYMrdj1ummvxncdFitDU3ewBkYZIlX';
            $access_token = ImageContentController::baidu_access_token($post_data, $keyToken_worker);
        } else {
            $access_token = $redis_token;
        }
        return $access_token;
    }
    /**
     * @description: 百度token 通用方法
     * @param {*} $post_data
     * @return {*}
     */
    public static function baidu_access_token($post_data, $keyToken_worker)
    {
        $url = 'https://aip.baidubce.com/oauth/2.0/token';
        $post_data['grant_type'] = 'client_credentials';
        $o = "";
        foreach ($post_data as $k => $v) {
            $o .= "$k=" . urlencode($v) . "&";
        }
        $post_data = substr($o, 0, -1);
        $res = ImageContentController::request_post($url, $post_data);
        //将获取到的access_token 保存到redis
        $res = CommonFun::str_change($res);
        $access_token = $res['access_token'];
        $expires_in = $res['expires_in']; // 这里需要完善，应该减掉一些时间，不然有可能出现token断层的情况
        Redis::setex($keyToken_worker, $expires_in, $access_token);
        return $access_token;
    }

    public static function request_post($url = '', $param = '')
    {
        if (empty($url) || empty($param)) {
            return false;
        }
        $postUrl = $url;
        $curlPost = $param;
        // 初始化curl
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $postUrl);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        // 要求结果为字符串且输出到屏幕上
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        // post提交方式
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
        // 运行curl
        $data = curl_exec($curl);
        curl_close($curl);

        return $data;
    }

    // private $signer;
    // private $httpClient;

    // function __construct(array $config)
    // {
    //   parent::__construct($config, 'apiexplorer');
    //   $this->signer = new BceV1Signer();
    //   $this->httpClient = new BceHttpClient();
    // }

    // private function sendRequest($httpMethod, array $varArgs, $path)
    // {
    //   $defaultArgs = array(
    //     'config' => array(),
    //     'body' => null,
    //     'headers' => array(),
    //     'params' => array(),
    //   );

    //   $args = array_merge($defaultArgs, $varArgs);
    //   if (empty($args['config'])) {
    //     $config = $this->config;
    //   } else {
    //     $config = array_merge(
    //       array(),
    //       $this->config,
    //       $args['config']
    //     );
    //   }
    //   if (!isset($args['headers'][HttpHeaders::CONTENT_TYPE])) {
    //     $args['headers'][HttpHeaders::CONTENT_TYPE] = HttpContentTypes::JSON;
    //   }
    //   $response = $this->httpClient->sendRequest(
    //     $config,
    //     $httpMethod,
    //     $path,
    //     $args['body'],
    //     $args['headers'],
    //     $args['params'],
    //     $this->signer
    //   );

    //   $result = $this->parseJsonResult($response['body']);
    //   $result->metadata = $this->convertHttpHeadersToMetadata($response['headers']);
    //   return $result;
    // }
}
